package com.supor.aiot.ui.privacy;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.helper.ActivityManager;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.ToastUtils;
import com.android.baseconfig.constact.AppGlobalHost;
import com.supor.aiot.R;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.base.BaseMVVMActivity;
import com.supor.aiot.common.base.NoViewModel;
import com.supor.aiot.common.ui.activity.WebActivity;
import com.supor.aiot.databinding.ActivityProtocolBinding;
import com.supor.aiot.helper.PrivacyProtocolHelper;

import androidx.annotation.NonNull;
import butterknife.OnClick;

/**
 * ---------------------------------------------------------------- <br>
 * Copyright (C) 2014-2020, by het, Shenzhen, All rights reserved.  <br>
 * ---------------------------------------------------------------- <br>
 * <p>
 * 描述: 隐私政策更新 <br>
 * 作者: lei <br>
 * 日期: 2020/10/17 <br>
 */
public class ProtocolActivity extends BaseMVVMActivity<NoViewModel, ActivityProtocolBinding> {

    CheckBox popCbPrivacy;
    Button popBtnNextStep;
    long userPrivacyTime = 0;
    long userServerTime = 0;

    PopupWindow popupWindow;

    @Override
    protected int resourceId() {
        return R.layout.activity_protocol;
    }

    @Override
    protected void initData() {
        super.initData();
        init(getIntent());
    }

    private void init(Intent intent) {
        userPrivacyTime = intent.getLongExtra(Constants.Key.USER_PRIVACY_TIME, 0);
        userServerTime = intent.getLongExtra(Constants.Key.USER_SERVER_TIME, 0);

        bindingView.setViewM(this);
        bindingView.btnCancel.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        bindingView.btnNextStep.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        bindingView.cbPrivacy.setOnCheckedChangeListener((buttonView, isChecked) -> {
            bindingView.btnNextStep.setBackgroundResource(isChecked ? R.drawable.bg_next :
                    R.drawable.bg_disable_for_click);
            bindingView.btnNextStep.setTextColor(isChecked ?
                    getResources().getColor(R.color.bg_next_color) :
                    getResources().getColor(R.color.white));
        });

        String tip = getString(R.string.privacy_text);
        SpannableString spannableString = new SpannableString(tip);
        ClickableSpan clickableSpan0 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                bindingView.cbPrivacy.setChecked(!bindingView.cbPrivacy.isChecked());
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan0, tip.indexOf("请您"), tip.indexOf(
                "请您") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERSERVERAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan1, tip.indexOf("用户"), tip.indexOf(
                "用户") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERPRIVACYAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan2, tip.indexOf("隐私"), tip.indexOf("隐私") + 6,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("用户") - 1, tip.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bindingView.tvPrivacyText.setText(spannableString);
        bindingView.tvPrivacyText.setHighlightColor(0x00000000);
        bindingView.tvPrivacyText.setMovementMethod(LinkMovementMethod.getInstance());
        // SuporPresenter.getInstance().reportVideoControl(2);
    }

    private void gotoPrivacy(String url) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.Key.param_type, 1);
        bundle.putString(Constants.Key.param_url, url);
        intent.putExtras(bundle);
        intent.setClass(this, WebActivity.class);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        // setResult(1);
        // finish();
        // overridePendingTransition(0, 0);
    }

    @Override
    protected boolean isUseBlackFontWithStatusBar() {
        return false;
    }

    @OnClick({R.id.btn_next_step, R.id.btn_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_next_step:
                if (!bindingView.cbPrivacy.isChecked()) {
                    ToastUtils.getInstance().showCustomToast(getResources().getString(R.string.privacy_disagree_toast));
                    return;
                }
                onAgree();
                break;
            case R.id.btn_cancel:
                if (popupWindow == null) {
                    initPop();
                }
                showPop(bindingView.llUpdate);
                bindingView.llUpdate.postDelayed(() -> bindingView.llUpdate.setVisibility(View.GONE), 50);

                // setResult(1);
                // finish();
                // overridePendingTransition(0, 0);
                // ThreadUtils.execute(this::cancel, 300);
                break;
        }
    }

    private void onAgree() {
        BaseSharedPreferences.setLong(this, Constants.Key.USER_PRIVACY_TIME,
                userPrivacyTime);
        BaseSharedPreferences.setLong(this, Constants.Key.USER_SERVER_TIME, userServerTime);
        setResult(0);
        finish();
        overridePendingTransition(0, 0);
        // SuporPresenter.getInstance().reportVideoControl(1);
        PrivacyProtocolHelper.UPDATE_PROTOCOL = false;
    }

    public void initPop() {
        popupWindow = new PopupWindow();
        View view = LayoutInflater.from(this).inflate(R.layout.pop_update_privacy, null);
        popupWindow.setContentView(view);
        popupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setBackgroundDrawable(null);
        popupWindow.setFocusable(false);//解决点击view重新打开popwindow的问题
        popupWindow.setOutsideTouchable(true);//点击外部popupwindow消失
        popupWindow.setAnimationStyle(R.style.privacy_popup_window_anim);

        popCbPrivacy = view.findViewById(R.id.cb_privacy);
        ImageView imageView = view.findViewById(R.id.iv_close);
        TextView tvPrivacyText = view.findViewById(R.id.tv_privacy_text);
        // 请您阅读完整版《用户服务协议》《隐私保护声明》
        String tip = getResources().getString(R.string.privacy_text);
        SpannableString spannableString = new SpannableString(tip);
        ClickableSpan clickableSpan0 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                popCbPrivacy.setChecked(!popCbPrivacy.isChecked());
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan0, tip.indexOf("请您"), tip.indexOf(
                "请您") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ClickableSpan clickableSpan1 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERSERVERAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan1, tip.indexOf("用户"), tip.indexOf(
                "用户") + 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ClickableSpan clickableSpan2 = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                gotoPrivacy(AppGlobalHost.getHost() + Constants.USERPRIVACYAGREE);
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }
        };
        spannableString.setSpan(clickableSpan2, tip.indexOf("隐私"), tip.indexOf("隐私") + 6,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        spannableString.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.colorPrimary)),
                tip.indexOf("用户") - 1, tip.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tvPrivacyText.setText(spannableString);
        tvPrivacyText.setHighlightColor(0x00000000);
        tvPrivacyText.setMovementMethod(LinkMovementMethod.getInstance());
        imageView.setOnClickListener(v -> popupWindow.dismiss());
        Button btnCancel = view.findViewById(R.id.btn_cancel);
        popBtnNextStep = view.findViewById(R.id.btn_next_step);
        btnCancel.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        popBtnNextStep.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
        popBtnNextStep.setBackgroundResource(bindingView.cbPrivacy.isChecked() ? R.drawable.bg_next :
                R.drawable.bg_disable_for_click);
        popBtnNextStep.setTextColor(bindingView.cbPrivacy.isChecked() ?
                getResources().getColor(R.color.bg_next_color) :
                getResources().getColor(R.color.white));
        popCbPrivacy.setChecked(bindingView.cbPrivacy.isChecked());
        popCbPrivacy.setOnCheckedChangeListener((buttonView, isChecked) -> {
            popBtnNextStep.setBackgroundResource(isChecked ? R.drawable.bg_next :
                    R.drawable.bg_disable_for_click);
            popBtnNextStep.setTextColor(isChecked ?
                    getResources().getColor(R.color.bg_next_color) :
                    getResources().getColor(R.color.white));
            bindingView.cbPrivacy.setChecked(isChecked);
        });
        btnCancel.setOnClickListener(v -> {
            // setResult(1);
            // finish();
            // overridePendingTransition(0, 0);
            cancel();
        });
        popBtnNextStep.setOnClickListener(v -> {
            if (!popCbPrivacy.isChecked()) {
                // Toast.makeText(this, "Hello mPaaS!", Toast.LENGTH_SHORT).show();
                ToastUtils.getInstance().showCustomToast(getResources().getString(R.string.privacy_disagree_toast));
                return;
            }
            onAgree();
        });

        /*
         * 退出popupWindow时取消暗背景
         */
        popupWindow.setOnDismissListener(() -> {
            bindingView.llUpdate.setVisibility(View.VISIBLE);
        });
    }

    public void showPop(View rootView) {
        if (popupWindow == null) {
            initPop();
        }
        popCbPrivacy.setChecked(bindingView.cbPrivacy.isChecked());
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void cancel() {
        // for huawei
        // onAgree();
        Activity activity = AppAgent.getCurrentActivity();
        Logc.d("activity: " + activity);
        if (activity != null && activity.getClass().getSimpleName().equalsIgnoreCase(
                "H5Activity")) {
            activity.onKeyDown(4, new KeyEvent(0, 4));
            activity.onBackPressed();
        }

        ActivityManager.finishAll();
    }
}